package com.coincalf.admin.web.funds.trading;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.coincalf.admin.annotation.Log;
import com.coincalf.admin.common.ResultMap;
import com.coincalf.admin.entity.TurnoverOrder;
import com.coincalf.admin.enums.SysLogTypeEnum;
import com.coincalf.admin.service.TurnoverOrderService;
import com.coincalf.admin.view.ReportCsvUtils;
import com.google.common.base.Strings;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.supercsv.cellprocessor.CellProcessorAdaptor;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.util.CsvContext;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;

/**
 * <p>
 * 成交订单 前端控制器
 * </p>
 *
 * @author Haliyo
 * @since 2018-5-16 16:48:09
 */
@Slf4j
@RestController
@RequestMapping("/turnoverOrder")
@Api(value = "成交订单", description = "成交订单管理")
public class TurnoverOrderController {

    @Autowired
    private TurnoverOrderService turnoverOrderService;

    @Log(value = "查询成交订单列表", type = SysLogTypeEnum.SELECT)
    @PreAuthorize("hasAuthority('trade_deal_order_query')")
    @GetMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "每页显示条数，默认 10", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderId", value = "订单ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用戶ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "订单类型:1 币币交易 2 创新交易", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "marketId", value = "交易市场ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "tradeType", value = "交易方式(1买 2卖)", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query"),
    })
    @ApiOperation(authorizations = {@Authorization(value = "Authorization")}, value = "按条件分页查询成交订单列表", httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功", response = TurnoverOrder.class),
            @ApiResponse(code = 1, message = "失败")

    })
    public Object selectPage(@ApiIgnore Page<TurnoverOrder> page,
                             String orderId, String userId, String type,
                             String marketId, String userName, String mobile,
                             String tradeType, String startTime, String endTime) {
        EntityWrapper<TurnoverOrder> ew = new EntityWrapper<>();
        if (!Strings.isNullOrEmpty(orderId)) {
            ew.eq("a.id", orderId);
        }
        if (!Strings.isNullOrEmpty(type)) {
            ew.eq("market_type", type);
        }
        if (!Strings.isNullOrEmpty(marketId)) {
            ew.eq("market_id", marketId);
        }
        if (!Strings.isNullOrEmpty(userName)) {
            ew.where("b.username like  '%" + userName + "%'").or().like("c.username", userName);
        }
        if (!Strings.isNullOrEmpty(userId)) {

            ew.like("a.sell_user_id", userId).or().like("a.buy_user_id", userId);
        }
        if (!Strings.isNullOrEmpty(mobile)) {
            ew.where("b.mobile like  '%" + mobile + "%'");
        }
        if (!Strings.isNullOrEmpty(tradeType)) {
            ew.eq("trade_type", tradeType);
        }
        if (!Strings.isNullOrEmpty(startTime)) {
            ew.ge("a.created", startTime);
        }
        if (!Strings.isNullOrEmpty(endTime)) {
            ew.le("a.created", endTime);
        }
        return ResultMap.getSuccessfulResult(turnoverOrderService.selectListPage(page, ew));
    }

    @Log(value = "成交订单导出", type = SysLogTypeEnum.EXPORT)
    @PreAuthorize("hasAuthority('trade_deal_order_export')")
    @RequestMapping({"/exportList"})
    @ResponseBody
    @ApiOperation(authorizations = {@Authorization(value = "Authorization")}, value = "成交订单导出", notes = "成交订单导出", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "每页显示条数，默认 10", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "订单类型:1 币币交易 2 创新交易", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "marketId", value = "交易市场ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用戶ID", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "买家", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "tradeType", value = "交易方式(1买 2卖)", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query"),
    })
    public void export(@ApiIgnore Page<TurnoverOrder> page, String type,
                       String marketId, String userId, String userName, String mobile,
                       String tradeType, String startTime, String endTime
            , HttpServletResponse response) throws Exception {
        EntityWrapper<TurnoverOrder> ew = new EntityWrapper<>();
        if (!Strings.isNullOrEmpty(type)) {
            ew.eq("market_type", type);
        }
        if (!Strings.isNullOrEmpty(marketId)) {
            ew.eq("market_id", marketId);
        }
        if (!Strings.isNullOrEmpty(userName)) {
            ew.where("b.username like  '%" + userName + "%'");
        }
        if (!Strings.isNullOrEmpty(userId)) {
            ew.like("a.sell_user_id", userId).or().like("a.buy_user_id", userId);
        }
        if (!Strings.isNullOrEmpty(mobile)) {
            ew.where("b.mobile like  '%" + mobile + "%'");
        }
        if (!Strings.isNullOrEmpty(tradeType)) {
            ew.eq("trade_type", tradeType);
        }
        if (!Strings.isNullOrEmpty(startTime)) {
            ew.ge("a.created", startTime);
        }
        if (!Strings.isNullOrEmpty(endTime)) {
            ew.le("a.created", endTime);
        }
        page.setCurrent(1);
        page.setSize(100000);//限制导出数量
        Page<TurnoverOrder> retPage = turnoverOrderService.selectListPage(page, ew);
        String[] header = {"订单ID", "交易市场", "买方订单ID", "买方用户ID", "卖方订单ID", "卖方用户ID", "订单类型", "成交价", "成交量", "成交买入手续费", "成交卖出手续费", "成交时间"};
        String[] properties = {"idStr", "marketName", "buyOrderId", "buyUserId", "sellOrderId", "sellUserId", "tradeTypeStr", "price", "volume", "dealBuyFee", "dealSellFee", "createdStr"};
        CellProcessor[] PROCESSORS = new CellProcessor[]{
                null,
                null,
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = "\t" + String.valueOf(value);
                        return v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = "\t" + String.valueOf(value);
                        return v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = "\t" + String.valueOf(value);
                        return v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = "\t" + String.valueOf(value);
                        return v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = "\t" + String.valueOf(value);
                        return v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = String.valueOf(value);
                        if (value != null) {
                            DecimalFormat df = new DecimalFormat("0.00000000");
                            v = df.format(value);
                        }
                        return "\t" + v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = String.valueOf(value);
                        if (value != null) {
                            DecimalFormat df = new DecimalFormat("0.00000000");
                            v = df.format(value);
                        }
                        return "\t" + v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = String.valueOf(value);
                        if (value != null) {
                            DecimalFormat df = new DecimalFormat("0.00000000");
                            v = df.format(value);
                        }
                        return "\t" + v;
                    }
                },
                new CellProcessorAdaptor() {
                    @Override
                    public String execute(Object value, CsvContext context) {
                        String v = String.valueOf(value);
                        if (value != null) {
                            DecimalFormat df = new DecimalFormat("0.00000000");
                            v = df.format(value);
                        }
                        return "\t" + v;
                    }
                },
                null
        };
        String fileName = "成交订单.csv";
        try {
            ReportCsvUtils.reportListCsv(response, header, properties, fileName, retPage.getRecords(), PROCESSORS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
